<?php
/**
 * 后台通用的页面
 */
declare(strict_types=1);

namespace App\Controller\Admin;

use App\Annotation\ModuleAndAction;
use App\Helper\CaptchaHelper;
use App\Helper\CookieHelper;
use App\Helper\FileHelper;
use App\Helper\JwtHelper;
use App\Helper\MenuHelper;
use App\Helper\ModuleHelper;
use App\Helper\RequestHelper;
use App\Middleware\AdminMiddleware;
use App\Model\AdminUser;
use Hyperf\HttpMessage\Stream\SwooleFileStream;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\Utils\Str;
use SplFileInfo;

/**
 * @AutoController()
 * @Middleware(AdminMiddleware::class)
 */
class PageController extends BaseController
{
    const ADMIN_UPLOAD_IMAGE_ROOT_PATH = BASE_PATH . '/storage/adminUploadImage';

    /**
     * Lay-ui-mini的菜单配置
     */
    public function init()
    {
        $userInfo = JwtHelper::decodeWithRequest(JwtHelper::ADMIN_JWT_TOKEN, $this->request);
        if (!$userInfo) {
            return $this->response->json([]);
        }
        $userModel = AdminUser::find($userInfo->data->id);
        if (!$userModel) {
            return $this->response->json([]);
        }
        if ($userModel->id == AdminUser::SUPER_ADMIN_ID) {
            $modules = ModuleHelper::getAllModules();
        } else {
            $modules = $userModel->admin_role->module_available ?? [];
        }
        $menuHelper = new MenuHelper($modules);
        $data = [
            'homeInfo' => [
                'title' => '管理后台',
                'href' => 'page/admin/index.html',
            ],
            'logoInfo' => [
                'title' => '管理后台',
                'image' => $userModel->image_url ?: '/images/admin_user_default.jpg',
                'href' => '',
            ],
            'menuInfo' => $menuHelper->getList(),
        ];
        return $this->response->json($data);
    }

    /**
     * 查看模块
     * @ModuleAndAction(module="管理后台:系统设置:通用", action="查看模块", icon="fa fa-cog")
     */
    public function index()
    {
        return $this->moduleAndActions();
    }

    /**
     * 查看模块
     * @ModuleAndAction(module="管理后台:系统设置:通用", action="查看模块")
     */
    public function moduleAndActions()
    {
        return $this->response->json(self::genSuccessData(ModuleHelper::getAllModuleAndActions()));
    }

    /**
     * 上传后台图片
     * @ModuleAndAction(module="管理后台:系统设置:通用", action="上传图片")
     */
    public function uploadImg()
    {
        $file = $this->request->file('file');
        if (!$file) {
            return $this->response->json(self::genErrorData('未选择上传的文件！'));
        }
        $path = date('Ymd') . '/';
        FileHelper::makeDir(self::ADMIN_UPLOAD_IMAGE_ROOT_PATH . '/' . $path);
        $path .= Str::random() . '.' . $file->getExtension();
        $file->moveTo(self::ADMIN_UPLOAD_IMAGE_ROOT_PATH . '/' . $path);
        if ($file->isMoved()) {
            return $this->response->json(self::genSuccessData(['src' => $path]));
        }
        return $this->response->json(self::genErrorData('保存失败！'));
    }

    /**
     * 查看后台图片
     * @ModuleAndAction(module="管理后台:系统设置:通用", action="查看图片")
     */
    public function showImg()
    {
        $path = $this->request->query('path', '');
        if (!$path) {
            return $this->response->withStatus(404);
        }
        $file = FileHelper::checkPath(self::ADMIN_UPLOAD_IMAGE_ROOT_PATH . '/' . $path, self::ADMIN_UPLOAD_IMAGE_ROOT_PATH);
        if (!$file || !file_exists($file) || !is_file($file)) {
            return $this->response->withStatus(404);
        }
        $file = new SplFileInfo($file);
        $contentType = FileHelper::getMineTypeByFileInfo($file);
        if (!$contentType || substr($contentType, 0, 6) !== 'image/') {
            return $this->response->withStatus(404);
        }
        return $this->response
            ->withHeader('content-type', $contentType)
            ->withBody(new SwooleFileStream($file));
    }

    /**
     * 验证码图片
     */
    public function captcha()
    {
        [$code, $content] = CaptchaHelper::genOne();
        $ip = RequestHelper::getClientIp($this->request);
        return $this->response
            ->withHeader('content-type', 'image/png')
            ->withCookie(CookieHelper::genOne(CaptchaHelper::ADMIN_COOKIE_NAME, CaptchaHelper::genCookieValue($code, $ip), 30))
            ->withContent($content);
    }
}
